﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace lxm.download.app.Model
{
    public class PictureModel
    {

        public string DownLoadUrl { get; set; }
        public string UserName { get; set; }
        public string Phone { get; set; }
        public string Time { get; set; }
        public string Day { get; set; }
        public string GetSaveFileName()
        {

            Uri uri = new Uri(DownLoadUrl);
            var filename = HttpUtility.UrlDecode(uri.Segments.Last());

            string ext = Path.GetFileName(filename);

            ext = ext.Substring(6);

            if (string.IsNullOrWhiteSpace(UserName))
            {
                return $"{Phone}_第{Day}天_{ext}";
            }

            var path= $"{UserName}_{Phone}_第{Day}天_{ext}";

            var newPath= this.GetValidName(path);

            if (!newPath.Equals(path))
            {
                return $"{Phone}_第{Day}天_{ext}";
            }
            else
            {
                return path;
            }
        }
       

        public  string GetValidName(string str)
        {

            string origin = str;
            try
            {
                //关键代码
                foreach (var a in str)
                {
                    byte[] bts = Encoding.UTF32.GetBytes(a.ToString());
                    if (bts[0].ToString() == "253" && bts[1].ToString() == "255")
                    {
                        str = str.Replace(a.ToString(), "");
                    }
                }
            }
            catch (Exception)
            {
                str = origin;
            }
            str = MakeValidFileName(str);
            return str;
        }

        public  string MakeValidFileName(string text, string replacement = "_")
        {
            StringBuilder str = new StringBuilder();
            var invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
            foreach (var c in text)
            {
                if (invalidFileNameChars.Contains(c))
                {
                    str.Append(replacement ?? "");
                }
                else
                {
                    str.Append(c);
                }
            }

            return str.ToString();
        }
    }
}
